﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using UnityEditor;

public class VideoPreviewWindow : EditorWindow
{

    private System.Object previewID;
    private VideoClip playingClip;
    private float videoSizeScale = 0.5f;

    [MenuItem("Test/Video Editor", priority = 100)]
    private static void showWindow()
    {
        var window = GetWindow<VideoPreviewWindow>("视频预览"); //(VideoPreviewWindow)ScriptableObject.CreateInstance<VideoPreviewWindow>();
        window.init("Assets/Videos/apply_video.mp4");
        window.Show();
    }

    public void init(string path)
    {
        playingClip = AssetDatabase.LoadAssetAtPath<VideoClip>(path);
        previewID = VideoPreviewTool.Play(playingClip);

        Vector2 size = new Vector2(playingClip.width * videoSizeScale, playingClip.height * videoSizeScale);

        this.maxSize = this.minSize = size;
        this.titleContent = new GUIContent("Video Editor Window");
    }

    private void Update()
    {
        if (EditorWindow.focusedWindow != this)
        {
            this.Close();
        }
    }

    private void OnGUI()
    {
        if (null != playingClip)
        {
            Texture pic = VideoPreviewTool.GetPreviewTexture(previewID);
            if (null != pic)
            {
                EditorGUI.DrawTextureTransparent(new Rect(0, 0, pic.width * videoSizeScale, pic.height * videoSizeScale), pic, ScaleMode.ScaleToFit);
            }

            Repaint();
        }
    }

    private void OnDestroy()
    {
        VideoPreviewTool.Stop(previewID);

        playingClip = null;
        previewID = null;
    }
}
